using System;
using System.ComponentModel;
using System.Windows;

namespace MC.Phone.Ads.Provider
{
    public abstract class BaseAdProvider : DependencyObject, IAdProvider
    {
        #region IAdProvider Members

        public abstract string Name { get; }
        public virtual string CountryCode { set; protected get; }

        [Browsable(false)]
        public virtual bool IsTest { get; set; }

        public abstract FrameworkElement ProvideAd();
        public event EventHandler<AdEventArgs> NewAd;
        public event EventHandler<AdEventArgs> NoAd;

        public void FireNoAd()
        {
            OnNoAd();
        }

        public event EventHandler<AdEventArgs> AdEngaged;
        public event EventHandler<AdErrorEventArgs> AdError;
        public abstract void Clean();

        #endregion

        protected void OnNewAd()
        {
            if (NewAd != null)
            {
                NewAd(this, new AdEventArgs {AdProviderName = Name});
            }
        }

        protected void OnNoAd()
        {
            if (NoAd != null)
            {
                NoAd(this, new AdEventArgs {AdProviderName = Name});
            }
        }

        protected void OnAdEngaged()
        {
            if (AdEngaged != null)
            {
                AdEngaged(this, new AdEventArgs {AdProviderName = Name});
            }
        }

        public void OnAdError(Exception exception)
        {
            if(AdError!=null)
            {
                AdError(this, new AdErrorEventArgs{AdProviderName = Name, Error = exception});
            }
            OnNoAd();
        }

        protected void ExecuteOnDispatcher(Action actionToExecute)
        {
            if (!Dispatcher.CheckAccess())
                Dispatcher.BeginInvoke(actionToExecute);
            else
                actionToExecute();
        }
    }
}